﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace LifeInSharePoint.PromotedLinks.Common.Receiver.OrderEventReceiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class OrderEventReceiver : SPItemEventReceiver
    {
        /// <summary>
        /// An item is being added.
        /// </summary>
        public override void ItemAdded(SPItemEventProperties properties)
        {
            base.ItemAdding(properties);
            updateOrder(properties, false);
        }

        /// <summary>
        /// An item was updated.
        /// </summary>
        public override void ItemUpdated(SPItemEventProperties properties)
        {
            base.ItemUpdated(properties);
            updateOrder(properties, false);
        }

        private void updateOrder(SPItemEventProperties properties, bool Delete)
        {
            this.EventFiringEnabled = false;
            SPListItem currentItem = properties.ListItem;
            int itemID = properties.ListItemId;

            int PromotedLinksOrder = Utilities.GetColumnIntValue(currentItem, "PromotedLinksOrder");

            SPList currentList = currentItem.ParentList;
            if (PromotedLinksOrder > currentList.ItemCount + 1 || PromotedLinksOrder == null)
            {
                int newCount = currentList.ItemCount;
                currentItem["PromotedLinksOrder"] = newCount;
                currentItem.Update();
            }

            SPQuery query = new SPQuery();
            query.Query = "<Where><And><Neq><FieldRef Name='ID' /><Value Type='Counter'>" + itemID + "</Value></Neq><Geq><FieldRef Name='PromotedLinksOrder' /><Value Type='Integer'>" + PromotedLinksOrder + "</Value></Geq></And></Where><OrderBy><FieldRef Name='PromotedLinksOrder' Ascending='True' /></OrderBy>";


            SPListItemCollection orderItems = currentList.GetItems(query);
            if (orderItems.Count > 0)
            {
                foreach (SPListItem item in orderItems)
                {
                    int Order = Utilities.GetColumnIntValue(item, "PromotedLinksOrder");
                    Order = Delete ? Order - 1 : Order + 1;
                    item["PromotedLinksOrder"] = Order;

                    item.Update();
                }
            }
            this.EventFiringEnabled = true;
        }

        /// <summary>
        /// An item is being deleted
        /// </summary>
        public override void ItemDeleting(SPItemEventProperties properties)
        {
            base.ItemDeleting(properties);
            updateOrder(properties, true);
        }

    }
}
